<template>
  <view class="pay-page">
    <!-- 顶部模式切换 -->
    <view class="delivery-mode-switcher">
      <view
        @tap="selectDeliveryType('delivery')"
        :class="{ active: deliveryType === 'delivery' }"
        >外卖配送</view
      >
      <view
        @tap="selectDeliveryType('pickup')"
        :class="{ active: deliveryType === 'pickup' }"
        >到店自取</view
      >
    </view>

    <!-- 主要内容 -->
    <scroll-view scroll-y class="main-content">
      <!-- 外卖配送信息卡片 (地址 + 时间) -->
      <view v-if="deliveryType === 'delivery'" class="card info-group-card">
        <!-- 地址行 -->
        <view class="info-row" @tap="chooseAddress">
          <view class="info-content">
            <template v-if="address">
              <view class="title"
                >{{ address.addressDetail }}{{ address.houseNumber }}</view
              >
              <view class="subtitle">{{ address.name }} {{ address.tel }}</view>
            </template>
            <template v-else>
              <view class="title placeholder">请选择收货地址</view>
            </template>
          </view>
          <u-icon
            name="arrow-right"
            size="16"
            color="#000"
            class="arrow-right-icon"
          ></u-icon>
        </view>

        <view class="divider"></view>

        <!-- 时间行 -->
        <view class="info-row" @tap="openTimePopup">
          <view class="info-content">
            <view class="title">送达时间</view>
          </view>
          <view class="value-with-arrow">
            <text class="value" :class="{ placeholder: !selectedTime }">
              {{
                selectedTime ? formatDateTime(scheduledDateTime) : '尽快送达'
              }}
            </text>
            <u-icon
              name="arrow-right"
              size="16"
              color="#000"
              class="arrow-right-icon"
            ></u-icon>
          </view>
        </view>
      </view>

      <!-- 到店自取信息卡片 (门店 + 时间) -->
      <view v-if="deliveryType === 'pickup'" class="card info-group-card">
        <!-- 门店行 -->
        <view class="info-row" @tap="openLocation">
          <view class="info-content">
            <view class="title">{{ shopInfo.name }}</view>
            <view class="subtitle">{{ shopInfo.address }}</view>
          </view>
        </view>

        <view class="divider"></view>

        <!-- 时间行 -->
        <view class="info-row" @tap="openTimePopup">
          <view class="info-content">
            <view class="title">自取时间</view>
          </view>
          <view class="value-with-arrow">
            <text class="value" :class="{ placeholder: !selectedTime }">
              {{ formatDateTime(scheduledDateTime) }}
            </text>
            <u-icon
              name="arrow-right"
              size="16"
              color="#000"
              class="arrow-right-icon"
            ></u-icon>
          </view>
        </view>
      </view>

      <!-- 订单详情卡片 -->
      <view class="card order-details-card">
        <!-- 商品清单 -->
        <view class="product-list">
          <view class="product-item" v-for="(item, index) in cart" :key="index">
            <image
              :src="item.image"
              class="product-image"
              mode="aspectFill"
            ></image>
            <view class="product-info">
              <view class="name">{{ item.name }}</view>
              <view class="specs">{{ item.specs }}</view>
            </view>
            <view class="price-quantity">
              <view class="price">
                <text class="symbol">¥</text>
                <text class="amount">{{ (item.price / 100).toFixed(2) }}</text>
              </view>
              <view class="quantity">x{{ item.number }}</view>
            </view>
          </view>
        </view>

        <!-- 费用明细 -->
        <view class="summary-details">
          <view class="summary-row">
            <text class="label">商品金额</text>
            <text class="value">¥{{ cartAmount }}</text>
          </view>
          <view
            class="summary-row"
            v-if="cart && cart.length > 0 && cart[0] && cart[0].freight"
          >
            <text class="label">配送费</text>
            <text class="value">¥{{ (cart[0].freight / 100).toFixed(2) }}</text>
          </view>
          <view class="summary-row interactive" @tap="openCouponSelector">
            <text class="label">优惠券</text>
            <view class="value-with-arrow">
              <text v-if="selectedCoupon" class="coupon-discount"
                >-¥{{ (selectedCoupon.discount / 100).toFixed(2) }}</text
              >
              <text
                v-else-if="availableCoupons.length > 0"
                class="coupon-available"
                >{{ availableCoupons.length }}张可用</text
              >
              <text v-else class="coupon-none">无可用</text>
              <u-icon
                name="arrow-right"
                size="16"
                color="#000"
                class="arrow-right-icon"
              ></u-icon>
            </view>
          </view>
          <view class="summary-row">
            <text class="label">订单备注</text>
            <input
              class="remark-input"
              v-model="remark"
              placeholder="选填，请输入备注信息"
              placeholder-class="input-placeholder"
            />
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部支付栏 -->
    <view class="payment-bar">
      <view class="total-section">
        <text class="label">合计：</text>
        <text class="amount-symbol">¥</text>
        <text class="amount-value">{{ finalAmount }}</text>
      </view>
      <button
        class="submit-btn"
        :class="{ disabled: !address && deliveryType === 'delivery' }"
        @tap="submitOrder"
        :disabled="!address && deliveryType === 'delivery'"
      >
        提交订单
      </button>
    </view>

    <!-- 统一的时间选择弹窗 -->
    <u-popup
      :show="showTimePopup"
      mode="bottom"
      border-radius="24"
      height="auto"
      @close="cancelTimeSelection"
    >
      <view class="time-popup">
        <view class="popup-header">
          <text class="title">{{
            deliveryType === 'delivery' ? '选择送达时间' : '选择自取时间'
          }}</text>
          <text class="close-btn" @click="cancelTimeSelection">×</text>
        </view>
        <view class="popup-content">
          <!-- 快速送达选项 -->
          <view
            class="time-option immediate-option"
            @tap="selectTimeOption(false)"
          >
            <view class="option-content">
              <text class="option-title"
                >尽快{{ deliveryType === 'delivery' ? '送达' : '自取' }}</text
              >
              <text class="option-desc"
                >预计一个小时内{{
                  deliveryType === 'delivery' ? '送达' : '可取'
                }}</text
              >
            </view>
            <view class="radio" :class="{ checked: !tempSelectedTime }"></view>
          </view>

          <!-- 预约时间选项 -->
          <view
            class="time-option schedule-option"
            @tap="selectTimeOption(true)"
          >
            <view class="option-content">
              <text class="option-title"
                >预约{{
                  deliveryType === 'delivery' ? '配送' : '自取'
                }}时间</text
              >
              <text class="option-desc" v-if="tempSelectedTime">
                {{ formatDateTime(tempScheduledDateTime || scheduledDateTime) }}
              </text>
            </view>
            <view class="radio" :class="{ checked: tempSelectedTime }"></view>
          </view>

          <!-- 内嵌时间选择器 -->
          <view class="time-picker-container" v-show="showInlineTimePicker">
            <picker-view
              class="time-picker-view"
              :value="pickerValue"
              @change="onInlinePickerChange"
            >
              <picker-view-column>
                <view
                  class="picker-item"
                  v-for="(date, index) in timeColumns[0]"
                  :key="'date-' + index"
                >
                  {{ date }}
                </view>
              </picker-view-column>
              <picker-view-column>
                <view
                  class="picker-item"
                  v-for="(hour, index) in timeColumns[1]"
                  :key="'hour-' + index"
                >
                  {{ hour }}
                </view>
              </picker-view-column>
              <picker-view-column>
                <view
                  class="picker-item"
                  v-for="(minute, index) in timeColumns[2]"
                  :key="'minute-' + index"
                >
                  {{ minute }}
                </view>
              </picker-view-column>
            </picker-view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @tap="confirmTimeSelection">确定</button>
        </view>
      </view>
    </u-popup>

    <!-- 优惠券选择弹窗 -->
    <u-popup
      v-model="showCouponPopup"
      mode="bottom"
      border-radius="24"
      height="70%"
    >
      <view class="coupon-popup">
        <view class="popup-header">
          <text class="title">选择优惠券</text>
          <text class="close-btn" @click="showCouponPopup = false">×</text>
        </view>
        <view class="popup-content">
          <view class="coupon-tabs">
            <view
              class="tab"
              :class="{ active: couponTab === 0 }"
              @tap="couponTab = 0"
              >可用 ({{ availableCoupons.length }})</view
            >
            <view
              class="tab"
              :class="{ active: couponTab === 1 }"
              @tap="couponTab = 1"
              >不可用 ({{ unavailableCoupons.length }})</view
            >
          </view>
          <scroll-view scroll-y class="coupon-scroll-view">
            <view class="coupon-list">
              <template v-if="couponTab === 0">
                <view class="no-coupon-option" @tap="clearSelectedCoupon">
                  <view
                    class="radio"
                    :class="{ checked: !selectedCoupon }"
                  ></view>
                  <text>不使用优惠券</text>
                </view>
                <view
                  class="coupon-ticket"
                  v-for="(coupon, index) in availableCoupons"
                  :key="index"
                  @tap="selectCoupon(coupon)"
                >
                  <view class="left-part">
                    <view class="value-line">
                      <text class="symbol">¥</text>
                      <text class="value">{{ coupon.discount / 100 }}</text>
                    </view>
                    <view class="condition-line"
                      >满{{ (coupon.minAmount / 100).toFixed(2) }}可用</view
                    >
                  </view>
                  <view class="right-part">
                    <view class="info">
                      <view class="name">{{ coupon.name }}</view>
                      <view class="expiry">{{ formatCouponTime(coupon) }}</view>
                    </view>
                    <view
                      class="radio"
                      :class="{
                        checked:
                          selectedCoupon && selectedCoupon.id === coupon.id
                      }"
                    ></view>
                  </view>
                </view>
                <view class="empty-list" v-if="availableCoupons.length === 0">
                  <text>暂无可用优惠券</text>
                </view>
              </template>
              <template v-else>
                <view
                  class="coupon-ticket disabled"
                  v-for="(coupon, index) in unavailableCoupons"
                  :key="index"
                >
                  <view class="left-part">
                    <view class="value-line">
                      <text class="symbol">¥</text>
                      <text class="value">{{ coupon.discount / 100 }}</text>
                    </view>
                    <view class="condition-line"
                      >满{{ (coupon.minAmount / 100).toFixed(2) }}可用</view
                    >
                  </view>
                  <view class="right-part">
                    <view class="info">
                      <view class="name">{{ coupon.name }}</view>
                      <view class="expiry">{{ formatCouponTime(coupon) }}</view>
                    </view>
                    <view class="reason">{{
                      getCouponUnavailableReason(coupon)
                    }}</view>
                  </view>
                </view>
                <view class="empty-list" v-if="unavailableCoupons.length === 0">
                  <text>暂无不可用优惠券</text>
                </view>
              </template>
            </view>
          </scroll-view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @tap="confirmCouponSelection">
            确定
          </button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  data() {
    return {
      cart: [],
      productInfo: null,
      address: null,
      selectedTime: false,
      scheduledDateTime: new Date().getTime(),
      showDatetimePicker: false,
      remark: '',
      minDate: new Date().getTime(),
      maxDate: new Date().getTime() + 7 * 24 * 60 * 60 * 1000, // 7天后
      addressList: [],
      timeColumns: [],
      deliveryType: 'delivery',
      // 优惠券相关
      showCouponPopup: false,
      couponTab: 0,
      userCoupons: [],
      selectedCoupon: null,
      availableCoupons: [],
      unavailableCoupons: [],
      // 时间选择相关
      showTimePopup: false,
      showInlineTimePicker: false,
      pickerValue: [0, 0, 0],
      tempSelectedTime: false,
      tempScheduledDateTime: null
    }
  },
  async onLoad(options) {
    // 获取店铺信息
    this.fetchShopInfo()

    // 设置最小时间为1小时后
    const now = new Date()
    const minDateTime = new Date(now.getTime() + 1 * 60 * 60 * 1000)
    const minutes = minDateTime.getMinutes()
    const roundedMinutes = minutes >= 30 ? 60 : 30
    const initialDate = new Date(minDateTime)
    initialDate.setMinutes(roundedMinutes, 0, 0)
    if (roundedMinutes === 60) {
      initialDate.setHours(initialDate.getHours() + 1)
      initialDate.setMinutes(0)
    }

    this.minDate = initialDate.getTime()
    this.scheduledDateTime = initialDate.getTime()
    this.maxDate = now.getTime() + 7 * 24 * 60 * 60 * 1000

    // 生成时间选项
    this.generateTimeColumns()

    // 先获取地址列表
    await this.getAddressList()

    if (options.productInfo) {
      this.productInfo = JSON.parse(decodeURIComponent(options.productInfo))
      this.cart = [
        {
          name: this.productInfo.name,
          price: this.productInfo.price,
          number: this.productInfo.number || 1,
          freight: this.productInfo.freight,
          image: this.productInfo.image,
          specs: this.productInfo.specs,
          id: this.productInfo.id,
          categoryId: this.productInfo.categoryId
        }
      ]
    } else {
      this.cart = uni.getStorageSync('cart') || []
    }

    // 加载优惠券
    this.loadCoupons()
  },
  computed: {
    ...mapGetters({
      shopInfo: 'shop/shopInfo'
    }),
    cartNum() {
      return this.cart.reduce((acc, cur) => acc + cur.number, 0)
    },
    cartAmount() {
      let amount = this.cart.reduce(
        (acc, cur) => acc + cur.number * cur.price,
        0
      )
      if (
        this.cart &&
        this.cart.length > 0 &&
        this.cart[0] &&
        this.cart[0].freight
      ) {
        amount += this.cart[0].freight
      }
      return (amount / 100).toFixed(2)
    },
    // 最终支付金额（减去优惠券金额）
    finalAmount() {
      let amount = parseFloat(this.cartAmount) * 100
      if (this.selectedCoupon) {
        amount = Math.max(0, amount - this.selectedCoupon.discount)
      }
      return (amount / 100).toFixed(2)
    },
    // 订单信息（用于优惠券匹配）
    orderInfo() {
      return {
        totalAmount: parseFloat(this.cartAmount) * 100,
        items: this.cart.map((item) => ({
          goodsId: item.id,
          categoryId: item.categoryId,
          price: item.price,
          number: item.number
        }))
      }
    }
  },
  methods: {
    ...mapActions({
      fetchShopInfo: 'shop/getShopInfo'
    }),
    openTimePopup() {
      this.showTimePopup = true
    },
    openLocation() {
      if (
        !this.shopInfo ||
        !this.shopInfo.latitude ||
        !this.shopInfo.longitude
      ) {
        uni.showToast({
          title: '门店信息不全，无法打开地图',
          icon: 'none'
        })
        return
      }
      uni.openLocation({
        latitude: parseFloat(this.shopInfo.latitude),
        longitude: parseFloat(this.shopInfo.longitude),
        name: this.shopInfo.name,
        address: this.shopInfo.address,
        scale: 18
      })
    },
    // 生成时间选项
    generateTimeColumns() {
      const dates = []
      const hours = []
      const minutes = ['00', '30']

      // 获取当前时间一小时后
      const now = new Date()
      const oneHourLater = new Date(now.getTime() + 1 * 60 * 60 * 1000)

      // 生成日期选项（今天到7天后）
      for (let i = 0; i < 8; i++) {
        const date = new Date(now.getTime() + i * 24 * 60 * 60 * 1000)
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        dates.push(`${month}月${day}日`)
      }

      // 生成小时选项
      // 如果是当天，则从当前时间1小时后开始；如果是其他天，则从0点开始
      const currentHour = oneHourLater.getHours()
      const minHour = 0
      const maxHour = 23

      for (let i = minHour; i <= maxHour; i++) {
        hours.push(i.toString().padStart(2, '0') + '时')
      }

      this.timeColumns = [dates, hours, minutes]
    },

    openTimePicker() {
      this.showTimePopup = true
    },

    onTimeConfirm(e) {
      const [dateStr, hourStr, minuteStr] = e.value
      const now = new Date()
      const selectedDate = new Date(now)

      // 解析选择的日期和时间
      const month = parseInt(dateStr.match(/(\d+)月/)[1])
      const day = parseInt(dateStr.match(/(\d+)日/)[1])
      const hour = parseInt(hourStr)
      const minute = parseInt(minuteStr)

      // 设置选择的日期和时间
      selectedDate.setMonth(month - 1)
      selectedDate.setDate(day)
      selectedDate.setHours(hour)
      selectedDate.setMinutes(minute)

      // 如果是当天，检查是否满足最小时间要求（当前时间1小时后）
      const minTime = new Date(now.getTime() + 1 * 60 * 60 * 1000)

      if (selectedDate.getTime() < minTime.getTime()) {
        uni.showToast({
          title: '请选择' + this.formatDateTime(minTime) + '之后的时间',
          icon: 'none'
        })
        return
      }

      this.scheduledDateTime = selectedDate.getTime()
      this.selectedTime = true
      this.showDatetimePicker = false
    },

    formatDateTime(timestamp) {
      const date = new Date(timestamp)
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${month}月${day}日 ${hours}:${minutes}`
    },
    // 获取地址列表
    async getAddressList() {
      try {
        const { errno, errmsg, data } = await this.$get('address/list', {
          page: 1,
          limit: 20
        })
        if (errno === 0) {
          this.addressList = data.list
          // 如果有地址，设置默认地址或第一个地址
          if (this.addressList.length > 0) {
            const defaultAddress = this.addressList.find(
              (addr) => addr.isDefault
            )
            this.address = defaultAddress || this.addressList[0]
            // 不需要额外构造地址字符串，直接使用原始数据
          } else {
            // 如果没有地址，提示用户添加地址
            uni.showToast({
              title: '请先添加收货地址',
              icon: 'none',
              duration: 2000
            })
            setTimeout(() => {
              uni.navigateTo({
                url: '/pages/addresses/add'
              })
            }, 2000)
          }
        } else {
          uni.showToast({
            title: errmsg,
            icon: 'none'
          })
        }
      } catch (error) {
        console.log(error)
        uni.showToast({
          title: '获取地址列表失败',
          icon: 'none'
        })
      }
    },
    chooseAddress() {
      uni.navigateTo({
        url: '/pages/addresses/index?source=checkout',
        events: {
          // 监听选择地址页面返回的数据
          addressSelected: (address) => {
            this.address = address
          }
        }
      })
    },
    // 更新地址（供地址选择页面调用）
    updateAddress(address) {
      this.address = address
    },
    selectDeliveryType(type) {
      this.deliveryType = type
    },
    // 加载优惠券
    async loadCoupons() {
      try {
        const res = await getAvailableCoupons({
          totalAmount: parseFloat(this.cartAmount) * 100
        })

        if (res.errno === 0) {
          this.userCoupons = res.data || []
          this.filterCoupons()

          // 自动选择最优优惠券
          this.selectOptimalCoupon()
        } else {
          uni.showToast({
            title: res.errmsg || '加载优惠券失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载优惠券失败', error)
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        })
      }
    },

    // 过滤优惠券（可用和不可用）
    filterCoupons() {
      // this.availableCoupons = this.userCoupons.filter(coupon =>
      // 	// isCouponAvailable(coupon, this.orderInfo)
      // )
      // this.unavailableCoupons = this.userCoupons.filter(coupon =>
      // 	!isCouponAvailable(coupon, this.orderInfo)
      // )
    },

    // 打开优惠券选择弹窗
    openCouponSelector() {
      this.showCouponPopup = true
    },

    // 选择优惠券
    selectCoupon(coupon) {
      this.selectedCoupon = coupon
    },

    // 清除选择的优惠券
    clearSelectedCoupon() {
      this.selectedCoupon = null
    },

    // 自动选择最优优惠券
    async selectOptimalCoupon() {
      try {
        // 方式一：本地计算最优优惠券
        const optimalCoupon = findOptimalCoupon(
          this.availableCoupons,
          this.orderInfo
        )

        // 方式二：调用后端接口获取最优优惠券
        // const res = await getOptimalCoupon(this.orderInfo)
        // const optimalCoupon = res.errno === 0 ? res.data : null

        this.selectedCoupon = optimalCoupon
      } catch (error) {
        console.error('自动选择最优优惠券失败', error)
      }
    },

    // 确认优惠券选择
    confirmCouponSelection() {
      this.showCouponPopup = false
    },

    // 格式化优惠券时间
    formatCouponTime(coupon) {
      if (!coupon.startTime || !coupon.endTime) return ''

      const start = new Date(coupon.startTime)
      const end = new Date(coupon.endTime)

      const startStr = `${start.getMonth() + 1}.${start.getDate()}`
      const endStr = `${end.getMonth() + 1}.${end.getDate()}`

      return `${startStr}-${endStr}有效`
    },

    // 获取优惠券不可用原因
    getCouponUnavailableReason(coupon) {
      const now = new Date().getTime()

      if (new Date(coupon.endTime).getTime() < now) {
        return '已过期'
      }

      if (new Date(coupon.startTime).getTime() > now) {
        return '未到使用时间'
      }

      if (this.orderInfo.totalAmount < coupon.minAmount) {
        return `未满${(coupon.minAmount / 100).toFixed(2)}元`
      }

      return '不适用于当前商品'
    },
    submitOrder() {
      if (this.deliveryType === 'delivery' && !this.address) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return
      }

      // 构建订单数据
      const orderData = {
        deliveryType: this.deliveryType,
        address: this.deliveryType === 'delivery' ? this.address : null,
        products: this.cart,
        deliveryTime:
          this.deliveryType === 'delivery' && !this.selectedTime
            ? 'immediate'
            : this.formatDateTime(this.scheduledDateTime),
        remark: this.remark,
        totalAmount: parseFloat(this.cartAmount) * 100,
        couponId: this.selectedCoupon ? this.selectedCoupon.id : null,
        couponDiscount: this.selectedCoupon ? this.selectedCoupon.discount : 0,
        finalAmount: parseFloat(this.finalAmount) * 100
      }

      // TODO: 调用创建订单接口
      console.log('提交订单', orderData)
    },
    // 打开时间选择弹窗时初始化临时变量
    openTimePopup() {
      // 获取当前时间一小时后的最近可用时间点
      const now = new Date()
      const minTime = new Date(now.getTime() + 1 * 60 * 60 * 1000)

      // 确保分钟只能是00或30
      const minutes = minTime.getMinutes()
      const roundedDate = new Date(minTime)

      if (minutes < 30) {
        roundedDate.setMinutes(30, 0, 0)
      } else {
        roundedDate.setHours(roundedDate.getHours() + 1)
        roundedDate.setMinutes(0, 0, 0)
      }

      // 初始化临时变量
      this.tempSelectedTime = this.selectedTime
      this.tempScheduledDateTime = this.selectedTime
        ? this.scheduledDateTime
        : roundedDate.getTime()

      // 设置选择器默认值
      const selectedDate = new Date(this.tempScheduledDateTime)
      const month = (selectedDate.getMonth() + 1).toString().padStart(2, '0')
      const day = selectedDate.getDate().toString().padStart(2, '0')
      const hour = selectedDate.getHours().toString().padStart(2, '0')
      const minute = selectedDate.getMinutes() >= 30 ? '30' : '00'

      // 找到对应的索引
      const dateIndex = this.timeColumns[0].findIndex(
        (date) => date === `${month}月${day}日`
      )
      const hourIndex = this.timeColumns[1].findIndex((h) => h === `${hour}时`)
      const minuteIndex = this.timeColumns[2].findIndex((m) => m === minute)

      // 设置picker-view的值
      this.pickerValue = [
        Math.max(0, dateIndex),
        Math.max(0, hourIndex),
        Math.max(0, minuteIndex)
      ]

      // 根据当前状态决定是否显示时间选择器
      this.showInlineTimePicker = this.tempSelectedTime

      // 显示弹窗
      this.showTimePopup = true
    },

    // 选择送达方式（立即/预约）
    selectTimeOption(isScheduled) {
      console.log('选择时间方式:', isScheduled ? '预约' : '立即')
      this.tempSelectedTime = isScheduled

      // 如果选择预约，显示时间选择器
      this.showInlineTimePicker = isScheduled

      // 如果选择立即送达，隐藏时间选择器
      if (!isScheduled) {
        this.showInlineTimePicker = false
      }

      // 强制更新视图
      this.$forceUpdate()
    },

    // 内嵌时间选择器变化
    onInlinePickerChange(e) {
      this.pickerValue = e.detail.value

      // 根据选择器的值更新临时日期时间
      const now = new Date()
      const selectedDate = new Date(now)

      const dateStr = this.timeColumns[0][this.pickerValue[0]]
      const hourStr = this.timeColumns[1][this.pickerValue[1]]
      const minuteStr = this.timeColumns[2][this.pickerValue[2]]

      const month = parseInt(dateStr.match(/(\d+)月/)[1])
      const day = parseInt(dateStr.match(/(\d+)日/)[1])
      const hour = parseInt(hourStr)
      const minute = parseInt(minuteStr)

      selectedDate.setMonth(month - 1)
      selectedDate.setDate(day)
      selectedDate.setHours(hour)
      selectedDate.setMinutes(minute)

      this.tempScheduledDateTime = selectedDate.getTime()
    },

    // 确认时间选择
    confirmTimeSelection() {
      // 如果选择的是预约配送，检查是否满足最小时间要求
      if (this.tempSelectedTime) {
        const now = new Date()
        const minTime = new Date(now.getTime() + 1 * 60 * 60 * 1000)

        if (this.tempScheduledDateTime < minTime.getTime()) {
          uni.showToast({
            title: '请选择' + this.formatDateTime(minTime) + '之后的时间',
            icon: 'none'
          })
          return
        }
      }

      // 更新实际的时间设置
      this.selectedTime = this.tempSelectedTime
      if (this.tempSelectedTime) {
        this.scheduledDateTime = this.tempScheduledDateTime
      }

      // 关闭弹窗
      this.showTimePopup = false
      this.showInlineTimePicker = false
    },

    // 取消时间选择
    cancelTimeSelection() {
      // 不保存修改，关闭弹窗
      this.showTimePopup = false
      this.showInlineTimePicker = false
    }
  }
}
</script>

<style lang="scss" scoped>
// 变量定义
$color-primary: #000000;
$color-primary-light: #f0f0f0;
$color-text-primary: #303133;
$color-text-secondary: #606266;
$color-text-placeholder: #000;
$color-border: #e4e7ed;
$color-bg: #f5f6f7;
$color-surface: #ffffff;
$color-accent-red: #000000;
$color-accent-orange: #000000;
$spacing-base: 8rpx;
$border-radius-base: 16rpx;
$border-radius-lg: 24rpx;
$font-size-sm: 24rpx;
$font-size-base: 28rpx;
$font-size-lg: 32rpx;
$shadow-base: 0 8rpx 20rpx rgba(0, 0, 0, 0.06);

// 全局样式
.pay-page {
  background-color: $color-bg;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji',
    'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
}

// 顶部模式切换
.delivery-mode-switcher {
  display: flex;
  padding: $spacing-base * 2 $spacing-base * 4;
  background-color: $color-surface;
  view {
    flex: 1;
    text-align: center;
    padding: $spacing-base * 1.5;
    font-size: $font-size-base;
    color: $color-text-secondary;
    border-radius: $border-radius-base;
    transition: all 0.3s ease;
    font-weight: 500;
    &.active {
      background-color: $color-primary-light;
      color: $color-primary;
      font-weight: 600;
    }
  }
}

.main-content {
  flex: 1;
  padding: $spacing-base * 2;
  overflow-y: auto;
  box-sizing: border-box;
  padding-bottom: 150rpx; /* 为底部栏留出空间 */
}

// 卡片基类
.card {
  background-color: $color-surface;
  border-radius: $border-radius-lg;
  margin: $spacing-base * 2;
  padding: $spacing-base * 3;
  box-shadow: $shadow-base;
}

// 信息组卡片 (地址/时间/门店)
.info-group-card {
  padding: 0 $spacing-base * 3;
  .info-row {
    display: flex;
    align-items: center;
    padding: $spacing-base * 3 0;
    .info-content {
      flex: 1;
      .title {
        font-size: $font-size-base;
        font-weight: 500;
        color: $color-text-primary;
        &.placeholder {
          font-weight: normal;
          color: $color-text-placeholder;
        }
      }
      .subtitle {
        font-size: $font-size-sm;
        color: $color-text-secondary;
        margin-top: $spacing-base / 2;
      }
    }
    .value-with-arrow {
      display: flex;
      align-items: center;
      font-size: $font-size-base;
      .value {
        color: $color-text-primary;
        font-weight: 500;
        &.placeholder {
          color: $color-accent-orange;
        }
      }
    }
    .arrow-right-icon {
      margin-left: $spacing-base;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .divider {
    height: 1rpx;
    background-color: $color-border;
  }
}

// 订单详情卡片
.order-details-card {
  // 商品列表
  .product-list {
    .product-item {
      display: flex;
      padding: $spacing-base * 3 0;
      border-bottom: 1rpx solid $color-border;
      &:last-child {
        border-bottom: none;
        padding-bottom: $spacing-base * 2;
      }
      &:first-child {
        padding-top: 0;
      }
    }
    .product-image {
      width: 140rpx;
      height: 140rpx;
      border-radius: 0;
      margin-right: $spacing-base * 3;
      background-color: #f7f7f7;
    }
    .product-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      .name {
        font-size: $font-size-base;
        color: $color-text-primary;
        font-weight: 500;
        line-height: 1.4;
      }
      .specs {
        font-size: $font-size-sm;
        color: $color-text-placeholder;
        margin-top: $spacing-base;
      }
    }
    .price-quantity {
      text-align: right;
      .price {
        font-weight: 600;
        color: $color-text-primary;
        .symbol {
          font-size: $font-size-sm;
        }
        .amount {
          font-size: $font-size-base;
        }
      }
      .quantity {
        font-size: $font-size-sm;
        color: $color-text-placeholder;
        margin-top: $spacing-base;
      }
    }
  }

  // 费用明细
  .summary-details {
    padding-top: $spacing-base * 2;
    border-top: 1rpx solid $color-border;
    .summary-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: $spacing-base * 2.5 0;
      font-size: $font-size-base;

      .label {
        color: $color-text-secondary;
      }
      .value {
        color: $color-text-primary;
        font-weight: 500;
      }

      &.interactive {
        cursor: pointer;
      }

      .value-with-arrow {
        display: flex;
        align-items: center;
        .coupon-discount {
          color: $color-accent-red;
          font-weight: 600;
        }
        .coupon-available {
          color: $color-accent-orange;
          font-weight: 500;
        }
        .coupon-none {
          color: $color-text-placeholder;
        }
        .arrow-right-icon {
          margin-left: $spacing-base;
        }
      }

      .remark-input {
        flex: 1;
        text-align: right;
        font-size: $font-size-base;
        color: $color-text-primary;
        margin-left: $spacing-base * 4;
      }
      .input-placeholder {
        color: $color-text-placeholder;
      }
    }
  }
}

// 底部支付栏
.payment-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: $spacing-base * 2 $spacing-base * 4;
  padding-bottom: calc(#{$spacing-base * 2} + env(safe-area-inset-bottom));
  background: $color-surface;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
  z-index: 100;

  .total-section {
    display: flex;
    align-items: baseline;
    color: $color-text-primary;
    .label {
      font-size: $font-size-base;
    }
    .amount-symbol {
      font-size: $font-size-base;
      font-weight: 600;
      color: $color-accent-red;
      margin-left: $spacing-base;
    }
    .amount-value {
      font-size: 44rpx;
      font-weight: 600;
      color: $color-accent-red;
    }
  }

  .submit-btn {
    background: #000000;
    color: #fff;
    border: none;
    border-radius: 0;
    padding: 0 40rpx;
    height: 76rpx;
    line-height: 76rpx;
    font-size: $font-size-base;
    font-weight: 600;
    margin: 0;
    box-shadow: none;
    &.disabled {
      background: #c8c9cc;
      box-shadow: none;
    }
  }
}

// 优惠券弹窗
.coupon-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: $color-bg;

  .popup-header {
    position: relative;
    text-align: center;
    padding: $spacing-base * 3;
    background-color: $color-surface;
    border-top-left-radius: $border-radius-lg;
    border-top-right-radius: $border-radius-lg;
    .title {
      font-size: $font-size-lg;
      font-weight: 600;
    }
    .close-btn {
      position: absolute;
      right: $spacing-base * 4;
      top: 50%;
      transform: translateY(-50%);
      font-size: 40rpx;
      color: $color-text-placeholder;
    }
  }

  .popup-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }

  .coupon-tabs {
    display: flex;
    background-color: $color-surface;
    padding: 0 $spacing-base * 2;
    .tab {
      flex: 1;
      text-align: center;
      padding: $spacing-base * 3 0;
      font-size: $font-size-base;
      color: $color-text-secondary;
      position: relative;
      font-weight: 500;
      &.active {
        color: $color-primary;
        font-weight: 600;
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 50rpx;
          height: 6rpx;
          background-color: $color-primary;
          border-radius: 3rpx;
        }
      }
    }
  }

  .radio {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    border: 1px solid #dcdfe6;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    background-color: #fff;
    &.checked {
      border-color: $color-primary;
      background-color: $color-primary;
      &::after {
        content: '✓';
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
      }
    }
  }

  .coupon-scroll-view {
    flex: 1;
    padding: $spacing-base * 2;
    .no-coupon-option {
      display: flex;
      align-items: center;
      background-color: $color-surface;
      padding: $spacing-base * 3;
      border-radius: $border-radius-base;
      margin: $spacing-base * 2;
      font-size: $font-size-base;
      color: $color-text-primary;
      .radio {
        margin-right: $spacing-base * 2;
      }
    }

    .coupon-ticket {
      display: flex;
      margin: $spacing-base * 2;
      filter: drop-shadow(0 4rpx 10rpx rgba(0, 0, 0, 0.04));

      .left-part {
        background: #000000;
        color: #fff;
        padding: $spacing-base * 3;
        border-top-left-radius: $border-radius-base;
        border-bottom-left-radius: $border-radius-base;
        text-align: center;
        position: relative;
        width: 180rpx;

        &::after {
          content: '';
          position: absolute;
          right: -10rpx;
          top: 50%;
          transform: translateY(-50%);
          width: 20rpx;
          height: 20rpx;
          background-color: $color-bg;
          border-radius: 50%;
        }

        .value-line {
          font-weight: 600;
          .symbol {
            font-size: $font-size-base;
          }
          .value {
            font-size: 52rpx;
          }
        }
        .condition-line {
          font-size: $font-size-sm;
          opacity: 0.8;
          margin-top: $spacing-base;
        }
      }

      .right-part {
        background: $color-surface;
        flex: 1;
        padding: $spacing-base * 3;
        border-top-right-radius: $border-radius-base;
        border-bottom-right-radius: $border-radius-base;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .info {
          .name {
            font-size: $font-size-base;
            font-weight: 600;
          }
          .expiry {
            font-size: $font-size-sm;
            color: $color-text-placeholder;
            margin-top: $spacing-base;
          }
        }
      }

      &.disabled {
        .left-part {
          background: #c8c9cc;
        }
        .right-part {
          background: #f7f7f7;
          color: $color-text-placeholder;
          .name {
            color: $color-text-placeholder;
          }
          .reason {
            font-size: $font-size-sm;
            color: $color-text-placeholder;
            text-align: right;
          }
        }
      }
    }

    .empty-list {
      text-align: center;
      color: $color-text-placeholder;
      padding: 100rpx 0;
    }
  }

  .popup-footer {
    padding: $spacing-base * 2 $spacing-base * 4;
    padding-bottom: calc(#{$spacing-base * 2} + env(safe-area-inset-bottom));
    background-color: $color-surface;
    border-top: 1rpx solid $color-border;
    .confirm-btn {
      background: #000000;
      color: #fff;
      border-radius: 0;
      height: 88rpx;
      line-height: 88rpx;
      font-size: $font-size-lg;
      font-weight: 600;
    }
  }
}

// 统一时间选择弹窗
.time-popup {
  display: flex;
  flex-direction: column;
  background-color: $color-bg;
  min-height: 600rpx;

  .popup-header {
    position: relative;
    text-align: center;
    padding: $spacing-base * 3;
    background-color: $color-surface;
    border-top-left-radius: $border-radius-lg;
    border-top-right-radius: $border-radius-lg;
    .title {
      font-size: $font-size-lg;
      font-weight: 600;
    }
    .close-btn {
      position: absolute;
      right: $spacing-base * 4;
      top: 50%;
      transform: translateY(-50%);
      font-size: 40rpx;
      color: $color-text-placeholder;
    }
  }

  .popup-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: $color-surface;
  }

  .time-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: $spacing-base * 3 $spacing-base * 4;
    border-bottom: 1rpx solid $color-border;
    background-color: $color-surface;

    .option-content {
      flex: 1;
      .option-title {
        font-size: $font-size-base;
        color: $color-text-primary;
        font-weight: 500;
      }
      .option-desc {
        font-size: $font-size-sm;
        color: $color-text-secondary;
        margin-top: $spacing-base;
      }
    }

    .radio {
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      border: 1px solid #dcdfe6;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;
      background-color: #fff;
      &.checked {
        border-color: $color-primary;
        background-color: $color-primary;
        &::after {
          content: '✓';
          color: #fff;
          font-size: 24rpx;
          font-weight: bold;
        }
      }
    }
  }

  .time-picker-container {
    padding: $spacing-base * 2;
    background-color: $color-surface;
    border-top: 1rpx solid $color-border;
    .time-picker-view {
      width: 100%;
      height: 480rpx;
    }
    .picker-item {
      line-height: 80rpx;
      text-align: center;
      font-size: $font-size-base;
    }
  }

  .popup-footer {
    padding: $spacing-base * 3;
    background-color: $color-surface;

    .confirm-btn {
      background: $color-primary;
      color: #fff;
      border-radius: 0;
      height: 88rpx;
      line-height: 88rpx;
      font-size: $font-size-base;
      font-weight: 600;
      width: 100%;
    }
  }
}
</style>
